<?php
/**
 * User: YL
 * Date: 2019/09/23
 */

namespace App\Middleware;

use Closure;
use Illuminate\Http\Request;

class AllowCrossDomain
{
    /**
     * 响应头
     * @var array
     */
    protected $header = [
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE',
        'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-Requested-With',
    ];

    /**
     * Handle an incoming request.
     *
     * @param  Request  $request
     * @param  Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $header = array_merge($this->header, config('app-cross', []));

        if (empty($header['Access-Control-Allow-Origin'])) {
            $origin = $request->header('origin');

            if ($origin) {
                $header['Access-Control-Allow-Origin'] = $origin;
            } else {
                $header['Access-Control-Allow-Origin'] = '*';
            }
        }

        if ($request->getMethod() === 'OPTIONS') {
            return response('', 204, $header);
        }

        return $next($request)->withHeaders($header);
    }
}
